<template>
  <CustomerLayout>
    <div class="order-detail-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <el-button 
          link 
          @click="goBack" 
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>订单详情</h2>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <!-- 订单内容 -->
      <div v-else-if="orderInfo.id" class="order-content">
        <!-- 未支付订单的支付倒计时 -->
        <div 
          v-if="orderInfo.status === 'ORDER_CREATED' && paymentCountdown"
          class="payment-countdown-section"
        >
          <div class="countdown-content">
            <el-icon class="countdown-icon"><Clock /></el-icon>
            <span class="countdown-text">
              订单将在 <strong class="countdown-time">{{ paymentCountdown }}</strong> 后自动取消
            </span>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="order-main-content">
          <!-- 左侧：订单状态和进度（仅配送中的订单显示进度条） -->
          <div v-if="shouldShowProgress" class="order-progress-sidebar">
            <OrderProgress
              :status="orderInfo.status || 'ORDER_CREATED'"
              :order-time="orderInfo.createTime"
              :pay-time="orderInfo.payTime"
              :accept-time="orderInfo.acceptTime"
              :prepare-time="orderInfo.prepareTime"
              :pickup-time="orderInfo.pickupTime"
              :deliver-time="orderInfo.deliverTime"
              :complete-time="orderInfo.completeTime"
            />
            
            <!-- 实时配送地图（仅配送中的订单显示） -->
            <div v-if="shouldShowMap" class="delivery-map-section">
              <!-- WebSocket连接状态指示器 -->
              <div class="ws-status-indicator">
                <el-icon :class="wsConnected ? 'connected' : 'disconnected'">
                  <span v-if="wsConnected">●</span>
                  <span v-else>●</span>
                </el-icon>
                <span class="status-text">
                  {{ wsConnected ? '实时连接中' : '连接断开' }}
                </span>
              </div>
              
              <el-button 
                type="primary" 
                @click="showDeliveryMap" 
                class="map-trigger-btn"
                :icon="Location"
                :disabled="!wsConnected"
              >
                {{ wsConnected ? '查看配送地图' : '等待连接中...' }}
              </el-button>
              
              <!-- 骑手位置信息显示 -->
              <div v-if="riderInfo.location" class="rider-location-info">
                <div class="location-item">
                  <span class="location-label">骑手当前位置:</span>
                  <span class="location-coords">
                    {{ riderInfo.location.latitude.toFixed(6) }}, {{ riderInfo.location.longitude.toFixed(6) }}
                  </span>
                </div>
                <div class="location-update-time">
                  <span class="update-label">最后更新:</span>
                  <span class="update-time">{{ new Date().toLocaleTimeString() }}</span>
                </div>
              </div>
              
              <!-- 手动获取位置按钮 -->
              <el-button 
                size="small" 
                @click="fetchRiderLocation" 
                class="refresh-location-btn"
                :icon="Refresh"
              >
                刷新骑手位置
              </el-button>
            </div>
          </div>

          <!-- 右侧：订单详情 -->
          <div class="order-details-content">
            <!-- 商家信息 -->
        <div class="store-section">
          <div class="section-title">
            <el-icon><Shop /></el-icon>
            商家信息
          </div>
          <div class="store-content">
            <!-- 商家基本信息 -->
            <div class="store-info" @click="goToStore">
              <el-image 
                :src="storeInfo.logo || storeInfo.coverImage" 
                fit="cover"
                class="store-logo"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="store-details">
                <div class="store-name">{{ storeInfo.name }}</div>
                <div class="store-rating">
                  <StarRating :score="storeInfo.rating || 5.0" :show-score="true" size="small" />
                  <span class="sales">月售{{ storeInfo.monthSales || 0 }}+</span>
                </div>
                <!-- 新增：商家状态和配送信息 -->
                <div class="store-meta">
                  <span class="delivery-info">
                    <el-icon size="14"><Clock /></el-icon>
                    {{ storeInfo.deliveryTime || 30 }}分钟
                  </span>
                  <span class="delivery-fee">配送费¥{{ (storeInfo.deliveryFee || 0).toFixed(2) }}</span>
                  <span class="min-order">起送¥{{ (storeInfo.minOrder || 0).toFixed(2) }}</span>
                </div>
              </div>
              <el-icon class="arrow-icon"><ArrowRight /></el-icon>
            </div>
            
            <!-- 新增：商家详细信息 -->
            <div class="store-extended-info">
              <div v-if="storeInfo.address" class="info-item">
                <el-icon size="14"><Location /></el-icon>
                <span class="info-label">地址：</span>
                <span class="info-value">{{ storeInfo.address }}</span>
              </div>
              <div v-if="storeInfo.phone" class="info-item">
                <el-icon size="14"><Phone /></el-icon>
                <span class="info-label">电话：</span>
                <span class="info-value">{{ storeInfo.phone }}</span>
              </div>
              <div v-if="storeInfo.businessHours" class="info-item">
                <el-icon size="14"><Clock /></el-icon>
                <span class="info-label">营业时间：</span>
                <span class="info-value">{{ storeInfo.businessHours }}</span>
              </div>
              <div v-if="storeInfo.description" class="info-item description">
                <el-icon size="14"><Document /></el-icon>
                <span class="info-label">简介：</span>
                <span class="info-value">{{ storeInfo.description }}</span>
              </div>
            </div>
            
            <!-- 商家操作按钮 -->
            <div class="store-actions">
              <el-button size="small" @click="contactStore">
                <el-icon><Phone /></el-icon>
                联系商家
              </el-button>
              <el-button size="small" type="primary" @click="reorder">
                再来一单
              </el-button>
            </div>
          </div>
        </div>

        <!-- 订单详情 -->
        <div class="order-section">
          <div class="section-title">
            <el-icon><List /></el-icon>
            订单详情
          </div>
          <div class="order-content-detail">
            <!-- 基本信息 -->
            <div class="order-basic-info">
              <div class="info-row">
                <span class="label">订单号：</span>
                <span class="value">{{ orderInfo.orderNo }}</span>
                <el-button link size="small" @click="copyOrderNo">复制</el-button>
              </div>
              <div class="info-row">
                <span class="label">下单时间：</span>
                <span class="value">{{ formatTime(orderInfo.createTime) }}</span>
              </div>
              <div v-if="orderInfo.remark" class="info-row">
                <span class="label">订单备注：</span>
                <span class="value">{{ orderInfo.remark }}</span>
              </div>
            </div>

            <!-- 商品列表 -->
            <div class="goods-list">
              <div v-for="item in orderInfo.items" :key="item.id" class="goods-item">
                <el-image 
                  :src="item.foodImage" 
                  :alt="item.foodName"
                  fit="cover"
                  class="goods-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="goods-info">
                  <div class="goods-name">{{ item.foodName }}</div>
                  <div v-if="item.attributes && item.attributes.length" class="goods-specs">
                    <span v-for="(attr, index) in item.attributes" :key="index">
                      {{ attr.name }}: {{ attr.options.join(', ') }}
                      <span v-if="index < item.attributes.length - 1">; </span>
                    </span>
                  </div>
                  <div class="goods-meta">
                    <span class="quantity">x{{ item.quantity }}</span>
                    <span class="price">¥{{ (item.subtotal || (item.price * item.quantity)).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 价格明细 -->
            <div class="price-details">
              <div class="price-item">
                <span>商品总价</span>
                <span>¥{{ orderInfo.goodsAmount?.toFixed(2) }}</span>
              </div>
              <div class="price-item">
                <span>配送费</span>
                <span>¥{{ orderInfo.deliveryFee?.toFixed(2) }}</span>
              </div>
              <div v-if="orderInfo.discountAmount" class="price-item discount">
                <span>优惠金额</span>
                <span>-¥{{ orderInfo.discountAmount.toFixed(2) }}</span>
              </div>
              <div class="price-item total">
                <span>实付金额</span>
                <span class="total-price">¥{{ orderInfo.paymentAmount?.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 配送信息 -->
        <div class="delivery-section">
          <div class="section-title">
            <el-icon><Van /></el-icon>
            配送信息
          </div>
          <div class="delivery-content">
            <div class="address-info">
              <div class="address-header">
                <el-icon><Location /></el-icon>
                <span class="address-label">收货地址</span>
              </div>
              <div class="address-detail">
                <div class="contact">
                  <span class="name">{{ orderInfo.address?.name }}</span>
                  <span class="phone">{{ orderInfo.address?.phone }}</span>
                </div>
                <div class="address">
                  {{ orderInfo.address?.province }}{{ orderInfo.address?.city }}{{ orderInfo.address?.district }}{{ orderInfo.address?.detail }}
                </div>
              </div>
            </div>
            
            <div v-if="riderInfo.name" class="rider-info">
              <div class="rider-header">
                <el-icon><User /></el-icon>
                <span class="rider-label">配送员</span>
              </div>
              <div class="rider-detail">
                <div class="rider-contact">
                  <span class="rider-name">{{ riderInfo.name }}</span>
                  <el-button link size="small" @click="contactRider">
                    <el-icon><Phone /></el-icon>
                    联系骑手
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="订单不存在或已被删除">
          <el-button type="primary" @click="goBack">返回上页</el-button>
        </el-empty>
      </div>

      <!-- 底部操作栏 -->
      <div v-if="orderInfo.id && orderActions.length > 0" class="action-bar">
        <template v-for="action in orderActions" :key="action.type">
          <el-button 
            v-if="action.type === 'pay'"
            type="primary" 
            size="large"
            @click="handlePay"
            :loading="paying"
            class="action-btn"
          >
            去支付
          </el-button>
          
          <el-button 
            v-else-if="action.type === 'cancel'"
            plain
            size="large"
            @click="handleCancel"
            class="action-btn"
          >
            取消订单
          </el-button>
          
          <el-button 
            v-else-if="action.type === 'urge'"
            plain
            size="large"
            @click="handleUrge"
            :disabled="!canUrge"
            class="action-btn"
          >
            {{ canUrge ? '催单' : `催单 (${Math.ceil((5 * 60 * 1000 - (Date.now() - lastUrgeTime)) / 60000)}分钟后可再次催单)` }}
          </el-button>
          
          <el-button 
            v-else-if="action.type === 'confirm'"
            type="primary"
            size="large"
            @click="handleConfirmReceived"
            class="action-btn"
          >
            确认收货
          </el-button>
          
          <el-button 
            v-else-if="action.type === 'review'"
            type="primary"
            size="large"
            @click="handleReview"
            class="action-btn"
          >
            评价订单
          </el-button>
          
          <el-button 
            v-else-if="action.type === 'reorder'"
            plain
            size="large"
            @click="reorder"
            class="action-btn"
          >
            再来一单
          </el-button>
        </template>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <PaymentDialog
      v-model:visible="paymentVisible"
      :order-info="orderInfo"
      :store-name="storeInfo.name"
      :address-info="addressInfo"
      :paying="paying"
      @pay="processPayment"
      @cancel="cancelPayment"
    />

    <!-- 配送地图弹窗 -->
    <DeliveryMap
      :visible="deliveryMapVisible"
      :order="orderInfo"
      :rider-info="riderInfo"
      :rider-location="riderInfo.location"
      :pickup-address="pickupAddressInfo"
      :delivery-address="deliveryAddressInfo"
      @close="closeDeliveryMap"
    />
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  ArrowRight, 
  Shop, 
  Picture, 
  List,
  Van,
  Location,
  User,
  Phone,
  Loading,
  Clock,
  Document,
  Refresh
} from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import StarRating from "@/components/common/StarRating.vue";
import OrderProgress from "@/components/customer/OrderProgress.vue";
import PaymentDialog from "@/components/customer/PaymentDialog.vue";
import DeliveryMap from "@/components/customer/DeliveryMap.vue";
import { orderApi, storeApi } from '@/api/customer';
import type { Order, Store } from '@/types/customer';
import { OrderStatus } from '@/types/customer';
import { wsService } from '@/utils/websocket';

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(true);
const paying = ref(false);
const paymentVisible = ref(false);
const deliveryMapVisible = ref(false); // 配送地图弹窗显示状态
const wsConnected = ref(false); // WebSocket连接状态
const lastUrgeTime = ref<number>(0); // 上次催单时间
const countdownTimer = ref<NodeJS.Timeout | null>(null); // 倒计时定时器
const autoCheckTimer = ref<NodeJS.Timeout | null>(null); // 自动检查定时器
const riderLocationTimer = ref<NodeJS.Timeout | null>(null); // 骑手位置更新定时器

const orderInfo = ref<Partial<Order>>({});
const storeInfo = ref<Partial<Store>>({});
const riderInfo = ref<any>({
  name: '',
  phone: '',
  location: {
    latitude: 0,
    longitude: 0
  }
});

// 计算属性
const addressInfo = computed(() => {
  const addr = orderInfo.value.address;
  if (!addr) return {
    latitude: 0,
    longitude: 0,
    address: ''
  };
  
  return {
    latitude: addr.latitude || 0,
    longitude: addr.longitude || 0,
    address: `${addr.province}${addr.city}${addr.district}${addr.detail}`
  };
});

// 商家地址信息（取餐地址）
const pickupAddressInfo = computed(() => {
  return {
    latitude: storeInfo.value.latitude || 0,
    longitude: storeInfo.value.longitude || 0,
    address: storeInfo.value.address || '商家地址',
    name: storeInfo.value.name || '商家',
    phone: storeInfo.value.phone || ''
  };
});

// 顾客配送地址信息
const deliveryAddressInfo = computed(() => {
  const addr = orderInfo.value.address;
  console.log('deliveryAddressInfo - addr:', addr);
  
  if (!addr) return {
    latitude: 0,
    longitude: 0,
    address: '配送地址',
    name: '',
    phone: ''
  };
  
  return {
    latitude: addr.latitude || 0,
    longitude: addr.longitude || 0,
    address: `${addr.province}${addr.city}${addr.district}${addr.detail}`,
    name: addr.name || '',
    phone: addr.phone || ''
  };
});

// 是否显示地图组件
const shouldShowMap = computed(() => {
  const status = orderInfo.value.status;
  return status === 'RIDER_ASSIGNED' || status === 'FOOD_PICKED';
});

// 是否显示进度条（排除待支付和已取消状态）
const shouldShowProgress = computed(() => {
  const status = orderInfo.value.status;
  return status !== 'ORDER_CREATED' && status !== 'CANCELLED';
});

// 预计送达时间
const estimatedDeliveryTime = computed(() => {
  // 根据订单创建时间计算预计送达时间
  if (!orderInfo.value.createTime) return '计算中...';
  
  const createTime = new Date(orderInfo.value.createTime);
  const estimatedTime = new Date(createTime.getTime() + 45 * 60 * 1000); // 假设45分钟送达
  
  return estimatedTime.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
});

// 支付倒计时（未支付订单15分钟倒计时）
const paymentCountdown = computed(() => {
  if (orderInfo.value.status !== 'ORDER_CREATED' || !orderInfo.value.createTime) {
    return null;
  }
  
  const createTime = new Date(orderInfo.value.createTime);
  const expireTime = new Date(createTime.getTime() + 15 * 60 * 1000); // 15分钟后过期
  const now = new Date();
  const remainingTime = expireTime.getTime() - now.getTime();
  
  if (remainingTime <= 0) {
    return '已过期';
  }
  
  const minutes = Math.floor(remainingTime / (60 * 1000));
  const seconds = Math.floor((remainingTime % (60 * 1000)) / 1000);
  
  return `${minutes}分${seconds}秒`;
});

// 检查订单是否已过期（15分钟）
const isOrderExpired = computed(() => {
  if (orderInfo.value.status !== 'ORDER_CREATED' || !orderInfo.value.createTime) {
    return false;
  }
  
  const createTime = new Date(orderInfo.value.createTime);
  const expireTime = new Date(createTime.getTime() + 15 * 60 * 1000); // 15分钟后过期
  const now = new Date();
  
  return now.getTime() >= expireTime.getTime();
});

// 自动取消过期订单
const autoCancel = async () => {
  try {
    console.log('订单已超时15分钟，自动取消订单:', orderInfo.value.id);
    
    await orderApi.cancelOrder(orderInfo.value.id!);
    ElMessage.warning('订单超时未支付，已自动取消');
    
    // 重新加载订单详情以更新状态
    await loadOrderDetail();
    
  } catch (error: any) {
    console.error('自动取消订单失败:', error);
    ElMessage.error('自动取消订单失败，请手动取消');
  }
};

// 启动自动检查定时器
const startAutoCheck = () => {
  // 清除现有定时器
  stopAutoCheck();
  
  // 只对未支付订单启动检查
  if (orderInfo.value.status !== 'ORDER_CREATED' || !orderInfo.value.createTime) {
    return;
  }
  
  // 每秒检查一次是否过期
  autoCheckTimer.value = setInterval(() => {
    if (isOrderExpired.value) {
      autoCancel();
      stopAutoCheck(); // 取消后停止检查
    }
  }, 1000);
  
  console.log('已启动订单过期自动检查定时器');
};

// 停止自动检查定时器
const stopAutoCheck = () => {
  if (autoCheckTimer.value) {
    clearInterval(autoCheckTimer.value);
    autoCheckTimer.value = null;
    console.log('已停止订单过期自动检查定时器');
  }
};

// 是否可以催单（限制频率：5分钟内只能催单一次）
const canUrge = computed(() => {
  const now = Date.now();
  return now - lastUrgeTime.value > 5 * 60 * 1000; // 5分钟
});

// 定义操作按钮类型
interface OrderAction {
  type: string;
  label: string;
}

const orderActions = computed((): OrderAction[] => {
  const status = orderInfo.value.status;
  if (!status) return [];
  
  const actions: OrderAction[] = [];
  
  // 根据新的状态定义设置操作按钮
  switch (status) {
    case 'ORDER_CREATED':
      // 待支付：支付 + 取消
      actions.push({ type: 'pay', label: '去支付' });
      actions.push({ type: 'cancel', label: '取消订单' });
      break;
    case 'PENDING':
      // 等待商家接单：催单 + 取消
      actions.push({ type: 'urge', label: '催单' });
      actions.push({ type: 'cancel', label: '取消订单' });
      break;
    case 'MERCHANT_CONFIRMED':
    case 'READY_WAITING_RIDER':
      // 商家已接单/等待骑手取餐：催单 + 取消
      actions.push({ type: 'urge', label: '催单' });
      actions.push({ type: 'cancel', label: '取消订单' });
      break;
    case 'RIDER_ASSIGNED':
    case 'FOOD_PICKED':
      // 骑手已接单/已取餐：催单
      actions.push({ type: 'urge', label: '催单' });
      break;
    case 'DELIVERED':
      // 已送达：确认收货 + 评价
      actions.push({ type: 'confirm', label: '确认收货' });
      actions.push({ type: 'review', label: '评价订单' });
      break;
    case 'COMPLETED':
      // 已完成：评价 + 再来一单
      actions.push({ type: 'review', label: '评价订单' });
      actions.push({ type: 'reorder', label: '再来一单' });
      break;
    case 'CANCELLED':
      // 已取消：再来一单
      actions.push({ type: 'reorder', label: '再来一单' });
      break;
  }
  
  return actions;
});

// 页面初始化
onMounted(() => {
  loadOrderDetail();
});

// 初始化WebSocket连接
const initWebSocket = (orderId: number) => {
  console.log('🔌 初始化WebSocket连接, 订单ID:', orderId);
  
  // 设置WebSocket事件监听
  wsService.onConnectionStatusChange = (connected: boolean) => {
    wsConnected.value = connected;
    console.log(`🔌 WebSocket连接状态变更: ${connected ? '已连接' : '已断开'}`);
  };
  
  wsService.onOrderStatusUpdate = (data: any) => {
    console.log('📋 收到订单状态更新:', data);
    // 更新本地订单状态
    if (data.orderId === orderInfo.value.id) {
      orderInfo.value.status = data.status;
      console.log('✅ 订单状态已更新为:', data.status);
    }
  };
  
  wsService.onRiderLocationUpdate = (data: any) => {
    console.log('🚴 收到骑手位置更新:', data);
    // 更新骑手位置信息
    if (data.orderId === orderInfo.value.id) {
      riderInfo.value.location = {
        latitude: data.latitude || data.lat,
        longitude: data.longitude || data.lng
      };
      console.log('✅ 骑手位置已更新:', riderInfo.value.location);
    }
  };
  
  // 建立WebSocket连接
  wsService.connectToOrder(orderId);
};

// 组件卸载时清理定时器和WebSocket连接
onUnmounted(() => {
  stopAutoCheck();
  stopRiderLocationUpdates();
  wsService.disconnect();
  console.log('🔌 组件卸载，WebSocket连接已断开');
});

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    // 先停止之前的定时器检查
    stopAutoCheck();
    
    loading.value = true;
    const orderId = Number(route.params.id); // 转换为数字类型
    
    if (!orderId || isNaN(orderId)) {
      ElMessage.error('无效的订单ID');
      return;
    }
    
    console.log('加载订单详情，订单ID:', orderId);
    
    const response = await orderApi.getOrderDetail(orderId);
    
    console.log('API完整响应:', response);
    console.log('API响应类型:', typeof response);
    console.log('API响应keys:', Object.keys(response));
    
    // 尝试找到实际的订单数据
    let orderData: any = null;
    
    // 情况1: 直接返回订单数据
    if ((response as any).id) {
      orderData = response;
      console.log('发现直接订单数据');
    }
    // 情况2: 嵌套在data字段中
    else if ((response as any).data && (response as any).data.id) {
      orderData = (response as any).data;
      console.log('发现嵌套订单数据 (response.data)');
    }
    // 情况3: 双重嵌套
    else if ((response as any).data && (response as any).data.data && (response as any).data.data.id) {
      orderData = (response as any).data.data;
      console.log('发现双重嵌套订单数据 (response.data.data)');
    }
    // 情况4: 其他可能的结构
    else {
      console.log('尝试查找订单数据的其他结构...');
      console.log('response:', response);
    }
    
    if (orderData && orderData.id) {
      console.log('找到订单数据:', orderData);
      
      // 处理地址信息
      let processedAddress: any = null;
      if (orderData.deliveryAddress) {
        const addr = orderData.deliveryAddress;
        console.log('原始deliveryAddress数据:', addr);
        processedAddress = {
          id: addr.id || 0,
          name: addr.receiver || '',
          phone: addr.phone || '',
          province: addr.province || '',
          city: addr.city || '',
          district: addr.district || '',
          detail: addr.detailAddress || '',
          latitude: addr.latitude || 0,
          longitude: addr.longitude || 0,
          isDefault: addr.isDefault === 1
        };
        console.log('处理后的地址信息:', processedAddress);
      }
      
      // 处理商品项目，确保字段匹配
      const processedItems = (orderData.items || []).map((item: any) => ({
        id: item.id,
        foodId: item.foodId,
        foodName: item.foodName,
        foodImage: item.foodImage || '',
        price: item.price || 0,
        quantity: item.quantity || 1,
        subtotal: item.amount || (item.price * item.quantity) || 0,
        attributes: item.attributes || [] // API可能没有返回属性信息
      }));
      
      // 组装完整的订单信息
      orderInfo.value = {
        id: orderData.id,
        orderNo: orderData.orderNo || `ORDER-${orderData.id}`,
        userId: orderData.userId || 0,
        storeId: orderData.storeId || 0,
        storeName: orderData.storeName || '未知商家',
        totalAmount: orderData.totalAmount || 0,
        deliveryFee: orderData.deliveryFee || 0,
        discountAmount: orderData.discountAmount || 0,
        paymentAmount: orderData.paymentAmount || orderData.totalAmount || 0,
        goodsAmount: orderData.totalAmount || 0, // 如果没有单独的商品金额，使用总金额
        status: orderData.status,
        remark: orderData.remark || '',
        createTime: orderData.createdAt || orderData.createTime || '',
        payTime: orderData.paidAt || '',
        acceptTime: orderData.acceptedAt || '',
        prepareTime: orderData.preparedAt || '',
        pickupTime: orderData.shippedAt || '',
        deliverTime: orderData.deliveredAt || '',
        completeTime: orderData.completedAt || '',
        items: processedItems,
        address: processedAddress
      };
      
      console.log('处理后的订单信息:', orderInfo.value);
      
      // 加载商家信息
      if (orderInfo.value.storeId) {
        await loadStoreInfo(orderInfo.value.storeId);
      }
      
      // 启动自动取消检查（仅对未支付订单）
      if (orderInfo.value.status === 'ORDER_CREATED') { // 未支付状态
        startAutoCheck();
      }
      
      // 启动骑手位置定期更新（仅配送状态）
      startRiderLocationUpdates();
      
      // 对于需要实时状态更新的订单，建立WebSocket连接
      if (shouldShowProgress.value && orderInfo.value.id) {
        initWebSocket(orderInfo.value.id);
      }
    } else {
      console.error('未找到有效的订单数据');
      ElMessage.error('订单数据格式错误');
    }
    
  } catch (error: any) {
    console.error('加载订单详情失败:', error);
    ElMessage.error(error.message || '加载订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 加载商家信息
const loadStoreInfo = async (storeId: number) => {
  try {
    console.log('加载商家信息，storeId:', storeId);
    
    const response = await storeApi.getStoreDetail(storeId.toString());
    console.log('商家API响应:', response);
    
    // 处理API响应结构，类似订单详情的处理方式
    let storeData: any = null;
    
    // 情况1: 直接返回商家数据
    if ((response as any).id) {
      storeData = response;
      console.log('发现直接商家数据');
    }
    // 情况2: 嵌套在data字段中
    else if ((response as any).data && (response as any).data.id) {
      storeData = (response as any).data;
      console.log('发现嵌套商家数据 (response.data)');
    }
    // 情况3: 双重嵌套
    else if ((response as any).data && (response as any).data.data && (response as any).data.data.id) {
      storeData = (response as any).data.data;
      console.log('发现双重嵌套商家数据 (response.data.data)');
    }
    
    if (storeData && storeData.id) {
      // 处理商家信息，确保字段名称匹配
      storeInfo.value = {
        id: storeData.id,
        name: storeData.name || '未知商家',
        description: storeData.description || '',
        logo: storeData.logo || storeData.avatar || '',
        coverImage: storeData.coverImage || storeData.cover || storeData.image || '',
        rating: storeData.rating || storeData.averageRating || 5.0,
        monthSales: storeData.monthSales || storeData.monthlySales || 0,
        deliveryTime: storeData.deliveryTime || storeData.averageDeliveryTime || 30,
        deliveryFee: storeData.deliveryFee || 0,
        minOrder: storeData.minOrder || storeData.minOrderAmount || 0,
        address: storeData.address || '',
        phone: storeData.phone || storeData.contactPhone || '',
        businessHours: storeData.businessHours || '营业中',
        status: storeData.status || 'OPEN',
        tags: storeData.tags || [],
        promotion: storeData.promotion || '',
        distance: storeData.distance || 0,
        // 添加坐标信息
        latitude: storeData.latitude || storeData.lat || 0,
        longitude: storeData.longitude || storeData.lng || 0
      };
      
      console.log('处理后的商家信息:', storeInfo.value);
    } else {
      console.error('未找到有效的商家数据');
      // 设置默认值，避免页面显示异常
      storeInfo.value = {
        id: storeId,
        name: '商家信息加载失败',
        description: '',
        logo: '',
        coverImage: '',
        rating: 5.0,
        monthSales: 0,
        deliveryTime: 30,
        deliveryFee: 0,
        minOrder: 0,
        address: '',
        phone: '',
        businessHours: '营业中',
        status: 'OPEN',
        tags: [],
        promotion: '',
        distance: 0,
        latitude: 0,
        longitude: 0
      };
    }
    
  } catch (error: any) {
    console.error('加载商家信息失败:', error);
    ElMessage.error(error.message || '加载商家信息失败');
    
    // 设置默认值，避免页面显示异常
    storeInfo.value = {
      id: storeId,
      name: '商家信息加载失败',
      description: '',
      logo: '',
      coverImage: '',
      rating: 5.0,
      monthSales: 0,
      deliveryTime: 30,
      deliveryFee: 0,
      minOrder: 0,
      address: '',
      phone: '',
      businessHours: '营业中',
      status: 'OPEN',
      tags: [],
      promotion: '',
      distance: 0,
      latitude: 0,
      longitude: 0
    };
  }
};

// 格式化时间
const formatTime = (time?: string): string => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 复制订单号
const copyOrderNo = async () => {
  try {
    await navigator.clipboard.writeText(orderInfo.value.orderNo || '');
    ElMessage.success('订单号已复制');
  } catch (error) {
    ElMessage.error('复制失败');
  }
};

// 跳转到商家页面
const goToStore = () => {
  router.push(`/customer/store/${orderInfo.value.storeId}`);
};

// 显示配送地图
const showDeliveryMap = () => {
  deliveryMapVisible.value = true;
};

// 关闭配送地图
const closeDeliveryMap = () => {
  deliveryMapVisible.value = false;
};

// 获取骑手位置
const fetchRiderLocation = async () => {
  if (!orderInfo.value.id) return;
  
  try {
    const response = await orderApi.getRiderLocation(orderInfo.value.id);
    console.log('获取骑手位置响应:', response);
    
    // 处理API响应结构，正确处理axios响应
    let locationData: any = null;
    const responseData = (response as any)?.data || response;
    
    if (responseData && typeof responseData === 'object') {
      // 情况1: 直接返回位置数据
      if (responseData.latitude !== undefined && responseData.longitude !== undefined) {
        locationData = responseData;
      }
      // 情况2: 嵌套在data字段中
      else if (responseData.data && responseData.data.latitude !== undefined) {
        locationData = responseData.data;
      }
      // 情况3: 双重嵌套
      else if (responseData.data && responseData.data.data && responseData.data.data.latitude !== undefined) {
        locationData = responseData.data.data;
      }
    }
    
    if (locationData && typeof locationData.latitude === 'number' && typeof locationData.longitude === 'number') {
      // 更新骑手位置信息
      riderInfo.value = {
        ...riderInfo.value,
        location: {
          latitude: locationData.latitude,
          longitude: locationData.longitude
        }
      };
      
      console.log('骑手位置已更新:', riderInfo.value.location);
    } else {
      console.warn('骑手位置数据格式无效:', responseData);
    }
    
  } catch (error: any) {
    console.error('获取骑手位置失败:', error);
    // 不显示错误提示，避免频繁打扰用户
  }
};

// 启动骑手位置定期更新
const startRiderLocationUpdates = () => {
  // 清除现有定时器
  stopRiderLocationUpdates();
  
  // 只在配送状态时启动位置更新
  const status = orderInfo.value.status;
  if (status !== 'RIDER_ASSIGNED' && status !== 'FOOD_PICKED') {
    console.log('订单状态不需要位置更新:', status);
    return;
  }
  
  console.log('启动骑手位置定期更新，订单状态:', status);
  
  // 立即获取一次位置
  fetchRiderLocation();
  
  // 每30秒更新一次位置
  riderLocationTimer.value = setInterval(() => {
    fetchRiderLocation();
  }, 30000); // 30秒间隔
  
  console.log('骑手位置定时器已启动');
};

// 停止骑手位置定期更新
const stopRiderLocationUpdates = () => {
  if (riderLocationTimer.value) {
    clearInterval(riderLocationTimer.value);
    riderLocationTimer.value = null;
    console.log('骑手位置定时器已停止');
  }
};

// 再来一单
const reorder = () => {
  router.push(`/customer/store/${orderInfo.value.storeId}`);
};

// 联系商家
const contactStore = () => {
  ElMessage.info('联系商家功能开发中');
};

// 联系骑手
const contactRider = () => {
  ElMessage.info('联系骑手功能开发中');
};

// 返回上页
const goBack = () => {
  router.back();
};

// 处理支付
const handlePay = () => {
  paymentVisible.value = true;
};

// 处理支付确认
const processPayment = async () => {
  paying.value = true;
  
  try {
    // 根据接口文档，支付接口需要的参数是 { orderId: number, paymentType?: string }
    const payResult = await orderApi.payOrder({
      orderId: orderInfo.value.id!,
      paymentType: 'WECHAT'
    });
    
    // 根据接口文档，返回格式应该是 { status: number, data: PaymentInfo }
    if (payResult.status === 200) {
      ElMessage.success('支付成功');
      paymentVisible.value = false;
      
      // 重新加载订单详情
      await loadOrderDetail();
      
    } else {
      const errorMsg = payResult.data?.message || payResult.data?.msg || '支付失败';
      throw new Error(errorMsg);
    }
    
  } catch (error: any) {
    console.error('支付失败:', error);
    ElMessage.error(error.message || '支付失败');
  } finally {
    paying.value = false;
  }
};

// 取消支付
const cancelPayment = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '确认取消', {
      confirmButtonText: '确定取消',
      cancelButtonText: '继续支付',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    });
    
    await orderApi.cancelOrder(orderInfo.value.id!);
    ElMessage.success('订单已取消');
    
    paymentVisible.value = false;
    await loadOrderDetail();
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error(error.message || '取消订单失败');
    }
  }
};

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '确认取消', {
      confirmButtonText: '确定取消',
      cancelButtonText: '我再想想',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    });
    
    await orderApi.cancelOrder(orderInfo.value.id!);
    ElMessage.success('订单已取消');
    await loadOrderDetail();
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error(error.message || '取消订单失败');
    }
  }
};

// 催单
const handleUrge = async () => {
  try {
    if (!canUrge.value) {
      ElMessage.warning('催单太频繁，请稍后再试');
      return;
    }
    
    // 根据接口文档，催单接口: POST /orders/{orderId}/urge
    await orderApi.urgeOrder(orderInfo.value.id!);
    
    // 更新上次催单时间
    lastUrgeTime.value = Date.now();
    
    ElMessage.success('催单成功，商家会尽快处理您的订单');
  } catch (error: any) {
    console.error('催单失败:', error);
    ElMessage.error(error.message || '催单失败');
  }
};

// 确认收货
const handleConfirmReceived = async () => {
  try {
    await ElMessageBox.confirm('确认已收到订单吗？', '确认收货', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'info'
    });
    
    // 根据接口文档，确认收货接口: PUT /orders/{id}/confirm
    await orderApi.confirmOrder(orderInfo.value.id!);
    ElMessage.success('确认收货成功');
    await loadOrderDetail();
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error);
      ElMessage.error(error.message || '确认收货失败');
    }
  }
};

// 评价订单
const handleReview = () => {
  // 跳转到评价页面，传递订单ID
  router.push(`/customer/order/${orderInfo.value.id}/review`);
};
</script>

<style scoped>
.order-detail-container {
  max-width: 95%;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 120px;
  min-width: 320px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-right: 15px;
  color: #666;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.loading-container p {
  margin-top: 15px;
}

/* 支付倒计时 */
.payment-countdown-section {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: white;
  padding: 15px 20px;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(255, 152, 0, 0.3);
}

.countdown-content {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.countdown-icon {
  font-size: 18px;
}

.countdown-time {
  color: #fff3e0;
  font-size: 16px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

/* 主要内容区域布局 */
.order-main-content {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  width: 100%;
}

/* 左侧进度条 */
.order-progress-sidebar {
  width: 35%;
  flex-shrink: 0;
  min-width: 280px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 实时配送地图区域 */
.delivery-map-section {
  width: 100%;
  max-width: 100%;
  overflow: hidden;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  text-align: center;
}

/* WebSocket连接状态指示器 */
.ws-status-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 12px;
}

.ws-status-indicator .el-icon.connected {
  color: #67C23A;
  animation: pulse 2s infinite;
}

.ws-status-indicator .el-icon.disconnected {
  color: #F56C6C;
}

.ws-status-indicator .status-text {
  color: #666;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.map-trigger-btn {
  width: 100%;
  height: 45px;
  font-size: 14px;
}

.rider-location-info {
  margin-top: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.location-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
}

.location-label {
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.location-coords {
  color: #333;
  font-family: monospace;
  font-size: 12px;
  background: #fff;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

.location-update-time {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.update-label {
  color: #999;
  margin-right: 8px;
}

.update-time {
  color: #666;
  font-family: monospace;
}

.refresh-location-btn {
  width: 100%;
  margin-top: 10px;
}

.map-trigger-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 右侧订单详情 */
.order-details-content {
  flex: 1;
  width: 65%;
  min-width: 0; /* 防止flex子项溢出 */
}

/* 通用区块样式 */
.store-section,
.order-section,
.delivery-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #eee;
  font-weight: 600;
  color: #333;
  gap: 8px;
}

/* 商家信息 */
.store-content {
  padding: 20px;
}

.store-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  cursor: pointer;
  transition: background-color 0.2s;
  padding: 10px;
  border-radius: 6px;
}

.store-info:hover {
  background: #f8f9fa;
}

.store-logo {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  margin-right: 15px;
}

.store-details {
  flex: 1;
}

.store-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
}

.store-rating {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.sales {
  color: #666;
  font-size: 12px;
}

/* 新增：商家配送信息 */
.store-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #666;
  flex-wrap: wrap;
}

.delivery-info,
.delivery-fee,
.min-order {
  display: flex;
  align-items: center;
  gap: 4px;
}

.arrow-icon {
  color: #999;
}

/* 新增：商家详细信息 */
.store-extended-info {
  margin: 15px 0;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item.description {
  align-items: flex-start;
}

.info-item .info-label {
  color: #666;
  min-width: 60px;
  flex-shrink: 0;
}

.info-item .info-value {
  color: #333;
  line-height: 1.4;
}

.store-actions {
  display: flex;
  gap: 10px;
}

/* 订单详情 */
.order-content-detail {
  padding: 20px;
}

.order-basic-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  min-width: 80px;
}

.value {
  color: #333;
  flex: 1;
}

/* 商品列表 */
.goods-list {
  margin-bottom: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 15px;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #ccc;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.goods-specs {
  font-size: 12px;
  color: #999;
  margin-bottom: 6px;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity {
  color: #666;
  font-size: 14px;
}

.price {
  color: #ff6600;
  font-weight: 600;
}

/* 价格明细 */
.price-details {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-item.discount {
  color: #67C23A;
}

.price-item.total {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: 600;
}

.total-price {
  color: #ff6600;
  font-size: 18px;
}

/* 配送信息 */
.delivery-content {
  padding: 20px;
}

.address-info,
.rider-info {
  margin-bottom: 20px;
}

.rider-info:last-child {
  margin-bottom: 0;
}

.address-header,
.rider-header {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.address-detail,
.rider-detail {
  padding-left: 22px;
}

.contact,
.rider-contact {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 6px;
}

.name,
.rider-name {
  font-weight: 600;
  color: #333;
}

.phone {
  color: #666;
  font-size: 14px;
}

.address {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 底部操作栏 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
  display: flex;
  gap: 15px;
  z-index: 100;
}

.action-btn {
  flex: 1;
  height: 44px;
}

/* 响应式设计 */
@media (min-width: 1400px) {
  .order-detail-container {
    max-width: 90%;
  }
  
  .order-progress-sidebar {
    width: 30%;
    min-width: 320px;
  }
  
  .order-details-content {
    width: 70%;
  }
}

@media (max-width: 1024px) {
  .order-detail-container {
    max-width: 100%;
    padding: 15px;
  }
  
  .order-main-content {
    gap: 15px;
  }
  
  .order-progress-sidebar {
    width: 40%;
    min-width: 250px;
  }
  
  .order-details-content {
    width: 60%;
  }
}

@media (max-width: 768px) {
  .order-detail-container {
    padding: 15px;
  }
  
  /* 移动端使用垂直布局 */
  .order-main-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .order-progress-sidebar {
    width: 100%;
    min-width: unset;
  }
  
  .order-details-content {
    width: 100%;
  }
  
  /* 地图组件移动端适配 */
  .delivery-map-section {
    width: 100%;
    max-width: 100%;
    overflow: hidden;
    margin: 0;
    padding: 10px;
    box-sizing: border-box;
    background: white;
    border-radius: 6px;
  }
  
  .store-actions {
    flex-direction: column;
  }
  
  .goods-item {
    gap: 10px;
  }
  
  .goods-image {
    width: 50px;
    height: 50px;
  }
  
  .info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .contact,
  .rider-contact {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  
  .action-bar {
    flex-direction: column;
    padding: 15px;
    gap: 10px;
  }
}
</style>
